﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace iNet.Media.Imaging.Bmp
{
	#region BitmapInfoHeader
	/// <summary>
	/// Windows 點陣圖資訊標頭。
	/// </summary>
	[StructLayout(LayoutKind.Sequential)]
	public struct BitmapInfoHeader
	{
		#region 欄位
		public uint Size;
		public int Width;
		public int Height;
		public ushort NumOfPlanes;
		public ushort BitCount;
		public uint Compression;
		public uint SizeImage;
		public int XPelsPerMeter;
		public int YPelsPerMeter;
		public uint ClrUsed;
		public uint ClrImportant;
		#endregion
		#region 建構子
		/// <summary>
		/// 以指定的資料流初始化 BitmapInfoHeader 結構欄位。
		/// </summary>
		/// <param name="stream">提供資料的資料流。</param>
		public BitmapInfoHeader(Stream stream)
			: this(stream, false)
		{ }
		/// <summary>
		/// 以指定的資料流初始化 BitmapInfoHeader 結構欄位。
		/// </summary>
		/// <param name="stream">提供資料的資料流。</param>
		/// <param name="restorePosition">資料讀取完畢後是否將資料流的位置恢復至讀取前的位置。</param>
		public BitmapInfoHeader(Stream stream, bool restorePosition)
		{
			//確認
			if (stream == null)
				throw new ArgumentNullException("stream");

			//讀取資料
			byte[] buffer = new byte[40];
			if (stream.Read(buffer, 0, 40) < 40)
				throw new EndOfStreamException();

			//恢復資料流位置
			if (restorePosition && stream.CanSeek)
				stream.Seek(-40, SeekOrigin.Current);

			//讀取欄位資料
			BitConverter converter = BitConverter.LittleEndian;
			this.Size = converter.ToUInt32(buffer, 0);
			this.Width = converter.ToInt32(buffer, 4);
			this.Height = converter.ToInt32(buffer, 8);
			this.NumOfPlanes = converter.ToUInt16(buffer, 12);
			this.BitCount = converter.ToUInt16(buffer, 14);
			this.Compression = converter.ToUInt32(buffer, 16);
			this.SizeImage = converter.ToUInt32(buffer, 20);
			this.XPelsPerMeter = converter.ToInt32(buffer, 24);
			this.YPelsPerMeter = converter.ToInt32(buffer, 28);
			this.ClrUsed = converter.ToUInt32(buffer, 32);
			this.ClrImportant = converter.ToUInt32(buffer, 36);
		}
		#endregion
	}
	#endregion
}
